package com.sc.security.service.impl;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sc.security.beans.LogService;
import com.sc.security.beans.Mail;
import com.sc.security.beans.PageQuery;
import com.sc.security.beans.PageResult;
import com.sc.security.common.RequestHolder;
import com.sc.security.dao.SysDeptMapper;
import com.sc.security.dao.SysUserMapper;
import com.sc.security.exception.ParamException;
import com.sc.security.model.SysDept;
import com.sc.security.model.SysUser;
import com.sc.security.service.LogType;
import com.sc.security.service.UserService;
import com.sc.security.utils.*;
import com.sc.security.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private LogService logService;


    @Override
    public void addUser(UserVo userVo) {
        BeanValidator.check(userVo);
        if(checkEmailExist(userVo.getMail(),null)){
            throw  new ParamException("邮箱已被占用");
        }
        if(checkPhoneExist(userVo.getTelephone(),null)){
            throw new ParamException("手机已被占用");
        }
        String password = "123";
        //String password = PasswordUtil.randomPassword();
        String encPass = MD5Util.encrypt(password);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userVo,user);
        user.setOperateTime(new Date());
        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateIp(IpUtil.getUserIP(RequestHolder.getCurrentRequest()));
        user.setId(null);
        user.setPassword(encPass);
        userMapper.insertSelective(user);
        logService.saveUserLog(null,user);
        sendMail(user.getMail(),password);
    }
    public void updateUser(UserVo userVo){
        BeanValidator.check(userVo);
        if(checkEmailExist(userVo.getMail(),userVo.getId())){
            throw  new ParamException("邮箱已被占用");
        }
        if(checkPhoneExist(userVo.getTelephone(),userVo.getId())){
            throw new ParamException("手机已被占用");
        }
        SysUser before = userMapper.selectByPrimaryKey(userVo.getId());
        Preconditions.checkNotNull(before,"用户信息不存在");
        SysUser after = new SysUser();
        BeanUtils.copyProperties(userVo,after);
        after.setOperateTime(new Date());
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getUserIP(RequestHolder.getCurrentRequest()));
        after.setPassword(before.getPassword());
        userMapper.updateByPrimaryKey(after);
        logService.saveUserLog(before,after);
    }

    @Override
    public SysUser login(String username) {
        return userMapper.login(username);
    }

    @Override
    public List<SysUser> getAll() {

        return userMapper.getAll();
    }

    @Override
    public PageResult<SysUser> listUser(Integer deptId, PageQuery pageQuery) {
        BeanValidator.check(pageQuery);
        int count  = userMapper.selectCountByDeptId(deptId);
        if(count>0){
            List<SysUser> userList = userMapper.selectUserList(deptId,pageQuery);
            PageResult pageResult = new PageResult();
            pageResult.setTotal(count);
            pageResult.setData(userList);
            return pageResult;
        }
        return new PageResult<>();
    }


    private boolean checkEmailExist(String email,Integer userId){
        if(userMapper.checkEmailExist(email,userId)>0){
            return true;
        }
        return false;
    }
    private boolean checkPhoneExist(String phone,Integer userId){
        if(userMapper.checkPhoneExist(phone,userId)>0){
            return true;
        }
        return false;
    }
    private void sendMail(String email,String password){
        Set<String> list = Sets.newHashSet();
        list.add(email);
        Mail mail = Mail.builder().subject("您已注册完成").
                message("您可以通过邮箱或手机号码登录系统，初始密码为"+password+"。请尽快登录并修改密码").
                receivers(list).build();
        MailUtil.send(mail);
    }
}
